<?php

namespace App\Service\Common;

use App\Constants\Redis\TempRedisCode;
use App\Model\Common\CategoryModel;
use App\Service\BaseService;
use App\Utils\Helper;
use Hyperf\Di\Annotation\Inject;

class CategoryService extends BaseService
{

    #[Inject]
    protected CategoryModel $categoryModel;

    public function addCategory($data, $adminId=0)
    {
        // 根节点必须有code
        if ($data['pid'] == '0' && !$data['code']){
            return [false,'根节点必须设置code'];
        }
        $lock = TempRedisCode::addCategoryLock($adminId);
        $this->lockError($lock);
        $r = $this->categoryModel->addOne($data);
        $this->freeLock($lock);
        if ($r){
            $this->categoryModel->refreshTree();
            return [true,'添加成功'];
        }
        return [false,'添加失败'];
    }

    public function getCategoryTreeFromDb()
    {
        return $this->categoryModel->treeFromDb();
    }

    public function updateCategory($id, $data)
    {
        $cate = $this->categoryModel->findById($id,['id']);
        if (!$cate){
            return [false,'分类数据不存在'];
        }
        $r = $this->categoryModel->updateById($id, $data);
        if ($r){
            $this->categoryModel->refreshTree();
            return [true,'更新成功'];
        }
        return [false,'没有改变'];
    }

    public function delCategory($ids)
    {
        $cateArr = $this->categoryModel->getSomeByIds($ids,['id']);
        if ($cateArr->isEmpty()){
            return [false,'数据不存在或者已删除'];
        }
        $r = $this->categoryModel->delByIds($ids);
        if ($r){
            $this->categoryModel->refreshTree();
            return [true,'删除成功'];
        }
        return [false,'删除失败'];
    }

    public function refreshTree()
    {
        $this->categoryModel->refreshTree();
        return [true,'刷新成功'];
    }


}